package com.frontop.terminal.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import com.frontop.terminal.constant.InterfaceConst;
import com.frontop.terminal.entity.Message;
import com.frontop.terminal.entity.PlayList;
import com.frontop.terminal.entity.TerminalConfig;
import com.frontop.terminal.enums.HeaderEnum;
import com.frontop.terminal.model.vo.RestResult;
import com.frontop.terminal.service.ICommandSerivce;
import com.frontop.terminal.util.ReadDataUtil;
import com.frontop.terminal.util.SystemMonitoringUtil;
import com.frontop.terminal.util.WriteDataUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 移除播放器列表资源
 * </p>
 *
 * @author Frontop
 * @since :2022-06-28
 **/
@Slf4j
public class PlayerRemoveResourceServiceImpl implements ICommandSerivce {

    /**
     * 执行业务
     *
     * @param message 消息对象
     * @return T
     */
    @SuppressWarnings({"ConstantConditions"})
    @Override
    public RestResult executeWork(Message message) {

        Map<Long, PlayList> playListMap = ReadDataUtil.getPlayListMap();
        if (null != playListMap && !playListMap.isEmpty()) {
            PlayList play = playListMap.get(Long.valueOf(message.getCommand()));
            if (null == play) {
                log.warn("要移除的资源不存在:{}", message.getCommand());
                return RestResult.failed("要移除的资源不存在");
            }

            playListMap.remove(Long.valueOf(message.getCommand()));

            List<PlayList> playLists = new ArrayList<>(playListMap.values());
            //保存
            WriteDataUtil.write(playLists, ReadDataUtil.PLAYLIST_LIST_CODING);

            //通知中控移除成功
            String mac = SystemMonitoringUtil.getMacAddress();
            TerminalConfig terminalConfig = ReadDataUtil.getTerminalConfig();

            //忽略通知结果
            if (ObjectUtil.isNotNull(terminalConfig)) {
                String url = terminalConfig.getServerAddress() + InterfaceConst.REMOVE_RESOURCE_SUCCESS;
                HttpRequest.post(url)
                        .header(HeaderEnum.TERMINAL_TOKEN.getKey(), ReadDataUtil.getTerminalConfig().getAuthorizationCode())
                        .form("mac", mac)
                        .form("id", message.getCommand())
                        .executeAsync();
            }

        }
        return RestResult.success();
    }
}
